package com.nowcoder.community.event;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.pojo.DiscussPost;
import com.nowcoder.community.pojo.Event;
import com.nowcoder.community.pojo.Message;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.ElasticsearchService;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import jdk.nashorn.internal.objects.annotations.Setter;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 将评论、点赞以及关注中的相关事件都通过消息队列的方式进行处理
 *
 * 生产者线程向消息队列中放数据，生产者线程放完数据后去执行其他操作，
 * 消费者从消息队列中取数据，取到数据后存放到数据库中
 */
@Component
public class EventConsumer implements CommunityConstant{
    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    @Qualifier("messageService")
    private MessageService messageService;

    @Autowired
    @Qualifier("discussPostService")
    private DiscussPostService discussPostService;

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Value("${wk.image.storage}")
    private String wkhtmltoimage;

    @Value("${wk.image.command}")
    private String wkImageCommand;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.share.name}")
    private String shareBucketName;

    //定时任务的线程池
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

//    @Autowired
    //单例模式。整个项目中的所有线程都只能创建一个对象
    private static ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {

        if(EventConsumer.threadPoolExecutor == null){
            synchronized (threadPoolExecutor){
                if(EventConsumer.threadPoolExecutor == null) {
                    EventConsumer.threadPoolExecutor = threadPoolExecutor;
                }
            }
        }
    }

    //获取触发的评论、点赞、关注事件
    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleEntityMessages(ConsumerRecord record, Acknowledgment ack){
        //判断消费者获取的数据是否为空
        if (record == null || record.value() == null){
            logger.error("实体的消息的内容为空！");
            return;
        }

        //将消费者获取到的事件由json转化成java对象的方式
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);

        if (event == null){
            logger.error("实体的消息格式错误！");
            return;
        }

        //---------------------------使用线程池
        /*//将事件中的信息添加到消息实例中
        //发送站内通知（由系统用户发送）
        Message message = new Message();
        //设置发送者为系统用户
        message.setFromId(SYSTEM_USER_ID);
        //设置发送的目标用户id
        message.setToId(event.getEntityUserId());
        //会话id为事件主题（主题由事件类型决定（评论、点赞、关注））
        message.setConversationId(event.getTopic());

        message.setCreateTime(new Date());

        //存放事件中的内容
        Map<String, Object> content = new HashMap<>();
        //将触发事件的用户id、事件作用的实体类型以及实体id存放到map集合中
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());

        //将事件中的其他数据转化成key-value的形式，然后存放到content中
        if (!event.getData().isEmpty()){
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }

        //向message中添加内容（将事件的所有信息都存到content属性中）
        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);*/

        //使用线程池来完成点赞、关注以及评论事件
        consumeEntityByThreadPool(event);

        //手动提交偏移量
        ack.acknowledge();
    }

    //获取发帖事件
    @KafkaListener(topics ={TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record, Acknowledgment ack){
        //判断消费者获取的数据是否为空
        if (record == null || record.value() == null){
            logger.error("发帖消息的内容为空！");
            return;
        }

        //将消费者获取到的事件由json转化成java对象的方式
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);

        if (event == null){
            logger.error("帖子消息格式错误！");
            return;
        }

        /*//当前实体类型为帖子，通过帖子id查出帖子
        DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());
        //将帖子添加到Elasticsearch中
        elasticsearchService.saveDiscussPost(discussPost);*/

        //使用线程池完成发帖事件
        consumePublishByThreadPool(event);

        //手动提交偏移量
        ack.acknowledge();
    }


    //获取删帖事件
    @KafkaListener(topics ={TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record, Acknowledgment ack){
        //判断消费者获取的数据是否为空
        if (record == null || record.value() == null){
            logger.error("消息的内容为空！");
            return;
        }

        //将消费者获取到的事件由json转化成java对象的方式
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);

        if (event == null){
            logger.error("消息格式错误！");
            return;
        }

        //当前实体类型为帖子，将当前id下的帖子从Elasticsearch中删除
        elasticsearchService.deleteDiscussPost(event.getEntityId());

        //手动提交偏移量
        ack.acknowledge();
    }

    //消费分享事件
    @KafkaListener(topics = TOPIC_SHARE)
    public void handleShareMessage(ConsumerRecord record, Acknowledgment ack){

        if(record == null || record.value() == null){
            logger.error("消息的内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if(event == null){
            logger.error("消息格式错误！");
            return;
        }

        String htmlUrl = (String) event.getData().get("htmlUrl");
        String fileName = (String) event.getData().get("fileName");
        String suffix = (String) event.getData().get("suffix");

        String cmd = wkImageCommand + " --quality 75 " + htmlUrl + " "
                + wkhtmltoimage + "/" + fileName + suffix;

        try {
            Runtime.getRuntime().exec(cmd);//执行cmd命令
            logger.info("生成长图成功：" + cmd);
        } catch (IOException e) {
            logger.error("生成长图失败：" + e.getMessage());
        }

        //启动定时器，监视该图片，一旦生成了，就上传至七牛云
        UploadTask task = new UploadTask(fileName, suffix);

        //每个500ms监视一次（也就是每个500ms执行一次这个任务，异步执行）
//        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(task, threadPoolTaskScheduler);
        Future future = threadPoolTaskScheduler.scheduleAtFixedRate(task, 500);
        task.setFuture(future);

        //手动提交偏移量
        ack.acknowledge();
    }



    private void consumeEntityByThreadPool(Event event){
//        System.out.println("---->" + threadPoolExecutor);
        threadPoolExecutor.submit(new ConsumeEntityMessagesTask(event));
        System.out.println("---->线程池结束");
    }

    private void consumePublishByThreadPool(Event event){
//        System.out.println("---->" + threadPoolExecutor);
        threadPoolExecutor.submit(new ConsumePublishMessageTask(event));
        System.out.println("---->线程池结束");
    }

    class ConsumeEntityMessagesTask implements Runnable{

        private Event event;

        public ConsumeEntityMessagesTask(Event event){
            this.event = event;
        }
        @Override
        public void run() {
            //将事件中的信息添加到消息实例中
            //发送站内通知（由系统用户发送）
            Message message = new Message();
            //设置发送者为系统用户
            message.setFromId(SYSTEM_USER_ID);
            //设置发送的目标用户id
            message.setToId(event.getEntityUserId());
            //会话id为事件主题（主题由事件类型决定（评论、点赞、关注））
            message.setConversationId(event.getTopic());

            message.setCreateTime(new Date());

            //存放事件中的内容
            Map<String, Object> content = new HashMap<>();
            //将触发事件的用户id、事件作用的实体类型以及实体id存放到map集合中
            content.put("userId", event.getUserId());
            content.put("entityType", event.getEntityType());
            content.put("entityId", event.getEntityId());

            //将事件中的其他数据转化成key-value的形式，然后存放到content中
            if (!event.getData().isEmpty()){
                for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                    content.put(entry.getKey(), entry.getValue());
                }
            }

            //向message中添加内容（将事件的所有信息都存到content属性中）
            message.setContent(JSONObject.toJSONString(content));
            messageService.addMessage(message);
        }
    }

    class ConsumePublishMessageTask implements Runnable{

        private Event event;

        public ConsumePublishMessageTask(Event event) {
            this.event = event;
        }

        @Override
        public void run() {
            //当前实体类型为帖子，通过帖子id查出帖子
            DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());
            //将帖子添加到Elasticsearch中
            elasticsearchService.saveDiscussPost(discussPost);
        }
    }

    class UploadTask implements Runnable{

        //文件名称
        private String fileName;

        //文件后缀
        private String suffix;

        //启动任务的返回值
        private Future future;

        //上传的开始时间
        private long startTime;

        //上传次数
        private int uploadTimes;

        public UploadTask(String fileName, String suffix) {
            this.fileName = fileName;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
        }

        public void setFuture(Future future) {
            this.future = future;
        }

        @Override
        public void run() {
            //生成文件失败（本地服务器出现故障）
            if(System.currentTimeMillis() - startTime >= 30000){
                logger.error("执行时间过长，终止任务：" + fileName);
                future.cancel(true);
                return;
            }

            //上传文件失败（七牛云服务器发生宕机）
            if(uploadTimes >= 3){
                logger.error("上传次数过多，终止任务：" + fileName);
                future.cancel(true);
                return;
            }

            //存放长图的本地路径
            String path = wkhtmltoimage + "/" + fileName + suffix;
            File file = new File(path);

            //如果生成了就开始上传（生成长图需要时间，可能要等待一会儿）
            if(file.exists()){
                logger.info(String.format("开始第%d次上传[%s]：", ++uploadTimes, fileName));

                //设置响应信息
                StringMap policy = new StringMap();
                policy.put("returnBody", CommunityUtil.getJSONString(0));

                //生成上传凭证
                Auth auth = Auth.create(accessKey, secretKey);
                String uploadToken = auth.uploadToken(shareBucketName, fileName, 3600, policy);

                //指定上传机房（华北）
                UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone1()));

                //开始上传图片
                try {
                    //上传
                    Response response = uploadManager.put(path, fileName, uploadToken, null,
                            "image/" + suffix, false);
                    //处理响应结果
                    JSONObject json = JSONObject.parseObject(response.bodyString());
                    if(json == null || json.get("code") == null || !json.get("code").toString().equals("0")){
                        logger.info(String.format("第%d次上传失败[%s]：", uploadTimes, fileName));
                    } else {
                        logger.info(String.format("第%d次上传成功[%s]：", uploadTimes, fileName));
                        future.cancel(true);
                    }
                } catch (QiniuException e) {
                    logger.error(String.format("第%d次上传失败[%s]：", uploadTimes, fileName));
                }
            } else {
                logger.info("等待图片生成[：" + fileName + "].");
            }
        }
    }

}
